package com.guigu.financial.service.impl;

import com.guigu.financial.enums.LendStatusEnum;
import com.guigu.financial.mapper.LendMapper;
import com.guigu.financial.pojo.BorrowInfo;
import com.guigu.financial.pojo.Lend;
import com.guigu.financial.pojo.vo.BorrowInfoApprovalVO;
import com.guigu.financial.service.LendService;
import com.guigu.financial.utils.LendNoUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

@Service
public class LendServiceImpl implements LendService {
    @Autowired
    private LendMapper lendMapper;

    @Override
    public void createLend(BorrowInfoApprovalVO borrowInfoApprovalVO, BorrowInfo borrowInfo) {
        Lend lend = new Lend();
        lend.setUserId(borrowInfo.getUserId());
        lend.setAmount(borrowInfo.getAmount());
        lend.setBorrowInfoId(borrowInfo.getId());
        lend.setLendNo(LendNoUtils.getLendNo());
        lend.setTitle(borrowInfoApprovalVO.getTitle());
        lend.setPeriod(borrowInfo.getPeriod());
        lend.setLendYearRate(borrowInfoApprovalVO.getLendYearRate().divide(new BigDecimal(100)));
        lend.setServiceRate(borrowInfoApprovalVO.getServiceRate().divide(new BigDecimal(100)));
        lend.setReturnMethod(borrowInfo.getReturnMethod());
        lend.setLowestAmount(new BigDecimal(100)); //最低投金额
        lend.setInvestAmount(new BigDecimal(0)); //已投资金额
        lend.setInvestNum(0); //以投人数

        lend.setPublishDate(new Date());

        // 计算起息日期
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate lendStartDate = LocalDate.parse(borrowInfoApprovalVO.getLendStartDate(), dateTimeFormatter);
        lend.setLendStartDate(lendStartDate);
        // 计算结算日期
        LocalDate lendEndDate = lendStartDate.plusMonths(borrowInfo.getPeriod());
        lend.setLendEndDate(lendEndDate);

        // 标的描述
        lend.setLendInfo(borrowInfoApprovalVO.getLendInfo());
        // 计算平台预期收益（根据年化率计算平台月化率，再乘以期数，乘以标的金额）
        BigDecimal monthRate = lend.getServiceRate().divide(new BigDecimal(12), 8, BigDecimal.ROUND_DOWN);
        BigDecimal expectAmount = lend.getAmount().multiply(monthRate.multiply(new BigDecimal(lend.getPeriod())));
        lend.setExpectAmount(expectAmount);
        // 实际收益
        lend.setRealAmount(new BigDecimal(0));
        // 设置标的状态
        lend.setStatus(LendStatusEnum.INVEST_RUN.getStatus());
        // 设置审核时间
        lend.setCheckTime(LocalDateTime.now());
        // 设置审核人
        lend.setCheckAdminId(1L);

        lendMapper.insertSelective(lend);
    }
}
